import type { FetchResponse, FetchRequestInit } from '@/utils/request'
import { NotifyPlugin } from 'tdesign-vue-next'
import { router } from '@/router'

const BASE_URL = import.meta.env.VITE_APP_BASE_API

export async function fetchRequest<T>(url: string, options: FetchRequestInit) {
  if (!window.fetch) throw new Error('fetch is not supported')
  const response = await window.fetch(BASE_URL.concat(url), options)
  if (!response.ok) {
    if (response.status === 401) {
      router.replace('/login')
    }
  }
  const json = (await response.json()) as FetchResponse<T>
  if (json.fail !== 0) {
    NotifyPlugin.error({ title: '失败', content: json.message ?? `出错了，请查看日志` })
  }
  console.log('Response = ', json)

  return json
}
